package com.example.springdemoelstic.service.impl;
import com.example.springdemoelstic.model.Person;
import com.example.springdemoelstic.repository.PersonRepository;
import com.example.springdemoelstic.service.PersonService;
import jdk.nashorn.internal.ir.ReturnNode;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import java.util.List;


@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    public PersonRepository personRepository;

    private static final Logger log = LoggerFactory.getLogger(PersonServiceImpl.class);

    /**
     * 添加
     * @param person
     * @return
     */
    @Override
    public Person save(Person person) {
        try {
            Person save = personRepository.save(person);
            log.info("用户添加" + save.toString());
            return save;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("在添加用户信息时报错");
            return null;
        }
    }

    /**
     * 批量添加
     * @param personList
     * @return
     */
    @Override
    public Iterable<Person> saveAll(List<Person> personList) {
        try {
            Iterable<Person> people = personRepository.saveAll(personList);
            for (Person person : people) {
                log.info("用户添加：" + person.toString());
            }
            return people;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批量添加时报错");
            return null;
        }
    }

    /**
     *删除
     * @param l
     * @return
     */
    @Override
    public boolean delete(long l) {
        // 主键删除
        personRepository.deleteById(1L);

        // 对象删除
        personRepository.findById(2L).ifPresent(person -> personRepository.delete(person));

//        // 批量删除
//        personRepository.deleteAll(personRepository.findAll());
        return true;

    }

    /**
     * 更新
     * @param person1
     * @return
     */
    @Override
    public boolean update(Person person1) {
        personRepository.findById(2L).ifPresent(person -> {
            person.setRemark(person.getRemark() + "\n更新更新更新");
            person.setName("曹操");
            Person save = personRepository.save(person);
            log.info("【save】= {}", save);
        });
        return true;
    }

    /**
     * 按生日排序
     */
    @Override
    public void select() {
        personRepository.findAll(Sort.by(Sort.Direction.DESC, "birthday"))
                .forEach(person -> log.info("{} 生日: {}", person.getName() + person.getBirthday()));

    }


    /**
     * 自定义高级查询
     * @param s
     */
    @Override
    public void customAdvanceSelect(String s) {
        // 构造查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本的分词条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
        // 排序条件
        queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
        // 分页条件
        queryBuilder.withPageable(PageRequest.of(0, 2));
        Page<Person> people = personRepository.search(queryBuilder.build());
        log.info("【people】总条数 = {}", people.getTotalElements());
        log.info("【people】总页数 = {}", people.getTotalPages());
        people.forEach(person -> log.info("【person】= {}，年龄 = {}", person.getName(), person.getAge()));

    }

    /**
     * 高级查询
     */
    @Override
    public void advanceSelect() {
        // QueryBuilders 提供了很多静态方法，可以实现大部分查询条件的封装
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "孙权");
        log.info("【queryBuilder】= {}", queryBuilder.toString());
        personRepository.search(queryBuilder).forEach(person -> log.info("【person】= {}", person));
    }


    /**
     * 自定义查询，根据年龄范围查询
     */
    @Override
    public Iterable<Person> findByAgeBetween(int i, int i1) {
        try {
            List<Person> people = personRepository.findByAgeBetween(i,i1);

            for (Person person : people) {
                log.info("用户查询:" + person.toString());
            }
            return people;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询报错");
            return null;
        }
    }




}
